﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace CloudShot.ImageStorages
{
	abstract class FileStorageBase : IImageStorage
	{
		protected readonly string _root;

		public abstract Image Logo { get; }
		public abstract string Name { get; }

		public ImageFormat[] SupportedFormats
		{
			get { return new[] { ImageFormat.Png, ImageFormat.Jpeg }; }
		}

		public abstract bool SupportsSaveToFileSystem { get; }

		public FileStorageBase(string root)
		{
			_root = root;
		}

		protected ShotInfo SaveImage(Image image, ImageFormat imageFormat, string filename)
		{
			Directory.CreateDirectory(_root);//create directory if not exist
			string pathToSave = Path.Combine(_root, filename);

			using (MemoryStream ms = new MemoryStream())
			using (FileStream fs = new FileStream(pathToSave, FileMode.Create))
			{
				image.Save(ms, imageFormat);
				ms.WriteTo(fs);
			}

			return new ShotInfo(filename, GetPublicUrl(pathToSave), pathToSave, image);
		}

		public virtual void SaveImageAsync(Image image, ImageFormat imageFormat, string name, Action<ShotInfo> saveCallback)
		{
			saveCallback(SaveImage(image, imageFormat, name));
		}

		public abstract bool IsShotInStorege(ShotInfo shotInfo);
		protected abstract Uri GetPublicUrl(string path);
	}
}
